<?php
namespace app\appauth\model;
use think\Log;
use think\Session;
use think\Validate;
use think\Db;
use app\base\model\Base;
class AuthM extends Base
{

       protected function _V($scene,$data)
       {
           $rule = [
               'org_name' => 'require',
           ];
        $msg = [];
        $field = [
            'org_name'=>'使用组织',
        ];
           $validate = new Validate($rule,$msg,$field);
           $validate->scene('add', ['org_name']);
           $result = $validate->scene($scene)->check($data);
           if($result === false)
           {
               return $validate->getError();
           }
           else
           {
               return true;
           }

       }


    /**
     * 新增数据
     * @return mixed
     */

    public function add($data)
    {
        $res = $this->_V('add',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $org_name = $data['org_name'];
        $app_secret = strtoupper(sha1(uniqid()));
        $res = Db::execute("insert into app_auth (app_key,app_secret,org_name) values(uuid(),'$app_secret','$org_name')");
        if($res === false)
        {
            $this->code = -1;
            $this->msg = '添加失败';
            return false;
        }
        return true;
    }

    /**
     * 全部数据
     */
    public function lst()
    {
        $data = Db::table('app_auth')
            ->field('app_id,app_key,app_secret,org_name')
            ->where(['is_usable'=>1])
            ->paginate(15);
        return $data;
    }

    /**
     * 修改数据
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        $app_secret = $data['app_secret'];
        if(empty($app_secret))
        {
            return true;
        }
        $app_secret = strtoupper(sha1($app_secret));
        $res = Db::table('app_auth')->where('app_id',$data['id'])->update(['app_secret'=>$app_secret]);
        if(!$res)
        {
            $this->code = -1;
            $this->msg = '修改失败';
            return false;
        }
        return true;
    }

    /**
     * 删除数据
     * @param $id
     */
    public function del($id)
    {
        return Db::table('app_auth')->where('app_id',$id)->update(['is_usable'=>0]);
    }

}
